import { reactive, ref,computed} from 'vue'
import { defineStore } from 'pinia'
import cookie from 'js-cookie'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { post } from '@/utlis/http'
//defineStore定义store，第一个是store的id（唯一标识符）
// 此函数的命名方式为use+defineStore的唯一标识符
interface userinfo {
  avatarUrl?: string;
  gmtCreate: number;
  gmtLastLogin: string;
  gmtUpdate: number;
  id: number;
  lastLoginIp: string;
  perms: string[];
  phone: string;
  realname: string;
  roleIds: number[];
  roles: string[];
  status: number;
  username: string;
}
export const useUserstore = defineStore('Userstore', () => {

  let router = useRouter()//跳转路由
  let user = ref(<userinfo>{})//类型
  let datanull = <userinfo>{}//定义空类型
  let users=reactive({//账户与密码
    username: '',
    password: ''
  })
  // 拿到个人信息
  const setuser = (data: userinfo) => {//登录页面的个人信息赋值给user
    user.value = data
  }
  // 计算属性拿到权限
  let permisstion=computed(()=>user.value.perms)
  //退出登录请求
  const loginout = () => {
    post({ _gp: 'admin', _mt: 'logout', }).then(res => {
      let { errno, errmsg } = res as any
      if (200 == errno) {
        ElMessage.success('退出' + errmsg)
        cookie.remove('token')//清除cookie
        user.value = datanull//清空状态管理
        router.replace('/login')//成功跳转登录页面
      } else {
        ElMessage.error(errmsg)//失败提醒用户失败原因
      }
    })
  }
  return { user,users, setuser, loginout,permisstion}
}, {
  persist: {
    paths:["user"]
  }
})

